package com.nageoffer.aicloud.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nageoffer.aicloud.common.convention.exception.ServiceException;
import com.nageoffer.aicloud.dao.entity.AnswerDO;
import com.nageoffer.aicloud.dto.req.OpenAIChatReqDTO;
import com.nageoffer.aicloud.dto.req.OpenAIDrawReqDTO;
import com.nageoffer.aicloud.dto.resp.OpenAIChatListRespDTO;
import com.nageoffer.aicloud.dto.resp.OpenAIChatRespDTO;
import com.nageoffer.aicloud.dto.resp.OpenAIDrawListRespDTO;
import com.nageoffer.aicloud.dto.resp.OpenAIDrawRespDTO;
import com.nageoffer.aicloud.service.AnswerService;
import com.nageoffer.aicloud.service.OpenAiService;
import com.nageoffer.aicloud.utils.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiImageModel;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ChatGPT 接口实现层
 */
@Service
@RequiredArgsConstructor
public class OpenAiServiceImpl implements OpenAiService {
    private final OpenAiChatModel openAiChatModel;
    private final OpenAiImageModel openAiImageModel;
    private final AnswerService answerService;

    @Override
    public OpenAIChatRespDTO openAiChatQuestion(OpenAIChatReqDTO requestParam) {
        String questionResult = openAiChatModel.call(requestParam.getQuestion());
        if (StrUtil.isNotBlank(questionResult)) {
            AnswerDO answerDO = AnswerDO.builder()
                    .title(requestParam.getQuestion())
                    .content(questionResult)
                    .model(1)
                    .type(1)
                    .uid(SecurityUtil.getUserDetails().getId())
                    .build();
            boolean saveResult = answerService.save(answerDO);
            if (saveResult) {
                return OpenAIChatRespDTO.builder()
                        .result(questionResult)
                        .build();
            } else {
                throw new ServiceException("问题答案保存数据库异常!");
            }
        }
        throw new ServiceException("问题回复异常，请稍候再试!");
    }

    @Override
    public OpenAIDrawRespDTO openAiDrawQuestion(OpenAIDrawReqDTO requestParam) {
        ImageResponse imageResponse = openAiImageModel.call(new ImagePrompt(requestParam.getQuestion()));
        String imageUrl = imageResponse.getResult().getOutput().getUrl();
        if (StrUtil.isNotBlank(imageUrl)) {
            AnswerDO answerDO = AnswerDO.builder()
                    .title(requestParam.getQuestion())
                    .content(imageUrl)
                    .model(1)
                    .type(2)
                    .uid(SecurityUtil.getUserDetails().getId())
                    .build();
            boolean saveResult = answerService.save(answerDO);
            if (saveResult) {
                return OpenAIDrawRespDTO.builder()
                        .imageUrl(imageUrl)
                        .build();
            } else {
                throw new ServiceException("绘图结果保存数据库异常!");
            }
        }
        throw new ServiceException("绘图结果异常，请稍候再试!");
    }

    @Override
    public List<OpenAIChatListRespDTO> getOpenAiChatList() {
        LambdaQueryWrapper<AnswerDO> queryWrapper = Wrappers.lambdaQuery(AnswerDO.class)
                .eq(AnswerDO::getType, 1)
                .eq(AnswerDO::getModel, 1)
                .eq(AnswerDO::getDelFlag, 0)
                .eq(AnswerDO::getUid, SecurityUtil.getUserDetails().getId())
                // 使用 id 避免回表查询
                .orderByDesc(AnswerDO::getId);
        List<AnswerDO> answerList = answerService.list(queryWrapper);
        List<OpenAIChatListRespDTO> openAIChatListRespList = BeanUtil.copyToList(answerList, OpenAIChatListRespDTO.class);
        return openAIChatListRespList;
    }

    @Override
    public List<OpenAIDrawListRespDTO> getOpenAiDrawList() {
        LambdaQueryWrapper<AnswerDO> queryWrapper = Wrappers.lambdaQuery(AnswerDO.class)
                .eq(AnswerDO::getType, 2)
                .eq(AnswerDO::getModel, 1)
                .eq(AnswerDO::getDelFlag, 0)
                .eq(AnswerDO::getUid, SecurityUtil.getUserDetails().getId())
                // 使用 id 避免回表查询
                .orderByDesc(AnswerDO::getId);
        List<AnswerDO> answerList = answerService.list(queryWrapper);
        List<OpenAIDrawListRespDTO> openAIDrawListRespList = BeanUtil.copyToList(answerList, OpenAIDrawListRespDTO.class);
        return openAIDrawListRespList;
    }
}
